package com.wx_shop.api.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import com.wx_shop.api.AppMainStarter;
import com.wx_shop.api.comm.ServiceCode;
import com.wx_shop.api.util.JWTHelperUtil;
import com.wx_shop.api.vo.UserVo;

/**
 * api 认证/授权验证
 */

public class JWTAuthenticationFilter extends BasicAuthenticationFilter {

	private static final Logger LOG = LoggerFactory.getLogger(JWTAuthenticationFilter.class);
	
	public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
		super(authenticationManager);
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		
		String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }
        
        boolean success = authentication(request, response);
        if( success ) {
        	chain.doFilter(request, response);
        }
	}
	
	private boolean authentication(HttpServletRequest request, HttpServletResponse response) {
		JWTHelperUtil jWTHelperUtil = AppMainStarter.applicationContext.getBean(JWTHelperUtil.class);
		
        String token = request.getHeader("Authorization");
        if( StringUtils.isNotEmpty(token) ) {
        	
        	try {
	        	UserVo mUserVo = jWTHelperUtil.verifyToken(token.replace("Bearer ", ""));
	        	
	        	ApiAuthenticationToken UPtoken = new ApiAuthenticationToken(mUserVo, null);
	            SecurityContextHolder.getContext().setAuthentication(UPtoken);
	            
	            // 网页的session为登录状态
	            // request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
	            
	            return true;
        	} catch(Exception e) {
        		
        		LOG.error("token={}, error={}", token, e.getMessage(), e);
        		
        		JSONObject jsonObj = new JSONObject();
    			try {
					jsonObj.put("status", ServiceCode.TOKEN_INVALID.status);
	    			jsonObj.put("message", ServiceCode.TOKEN_INVALID.message);
	        			
	        		response.setContentType("text/json");
	        		response.getWriter().println(jsonObj.toString());
    			} catch (Exception e1) {
					e1.printStackTrace();
				}
        	}
        }
        return false;
    }
}
